<template>
  <div>
    <el-main class="nopadding">
      <ax-table
        id="axtableId"
        ref="table"
        :row-config="{
          useKey: 'id',
        }"
        show-overflow
        :data="tableDatas"
        :scroll-y="{ enabled: true, gt: 0 }"
        hide-pagination
        :columns="[]"
        :footer-method="footerMethod"
        show-footer
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
        }"
        :custom-config="{
          mode: 'popup',
          storage: {
            visible: true,
            resizable: true,
            sort: true,
            fixed: true,
          },
        }"
        stripe
        border
        :header-cell-style="{ backgroundColor: '#edf1f3' }"
        @selection-change="selectionChange"
      >
        <vxe-column type="checkbox" width="70"></vxe-column>
        <vxe-column type="seq" width="70"></vxe-column>
        <vxe-column field="abstractName" title="摘要" width="130" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input v-model="scope.row.abstractName" placeholder="" clearable @focus="selectData($event, scope)">
              <template #append>
                <el-button :icon="Search" @click="openAbstract(scope)" />
              </template>
            </el-input>
          </template>
        </vxe-column>
        <vxe-column field="subjectIdName" title="总帐科目" width="260" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input v-model="scope.row.subjectIdName" placeholder="" clearable @focus="selectData($event, scope)">
              <template #append>
                <el-button :icon="Search" @click="openSubject(scope)" />
              </template>
            </el-input>
          </template>
        </vxe-column>
        <vxe-column field="buysSalesIdName" title="明细科目" width="230" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input v-model="scope.row.buysSalesIdName" placeholder="" clearable>
              <template #append>
                <el-button :icon="Search" @click="openBuysSale(scope)" />
              </template>
            </el-input>
          </template>
        </vxe-column>
        <vxe-column field="assistNumber" title="原币数量" width="110" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input
              :id="'txt_' + scope.rowIndex + '_0'"
              v-model="scope.row.assistNumber"
              placeholder=""
              input-style="text-align: right"
              @change="changeData(scope)"
              @focus="selectData($event, scope)"
              @keyup.enter="gotoNext($event, scope, 0)"
            />
          </template>
        </vxe-column>
        <vxe-column field="rate" title="汇率单价" width="110" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input
              :id="'txt_' + scope.rowIndex + '_1'"
              v-model="scope.row.rate"
              placeholder=""
              input-style="text-align: right"
              @focus="selectData($event, scope)"
              @keyup.enter="gotoNext($event, scope, 1)"
            />
          </template>
        </vxe-column>
        <vxe-column field="mainDebit" title="借方金额" width="110" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input
              :id="'txt_' + scope.rowIndex + '_2'"
              v-model="scope.row.mainDebit"
              placeholder=""
              input-style="text-align: right"
              @change="changeData(scope, 'mainDebit')"
              @focus="selectData($event, scope)"
              @keyup.enter="gotoNext($event, scope, 2)"
            />
          </template>
        </vxe-column>
        <vxe-column field="mainCredit" title="货方金额" width="110" align="center" :edit-render="{}">
          <template #edit="scope">
            <el-input
              :id="'txt_' + scope.rowIndex + '_3'"
              v-model="scope.row.mainCredit"
              placeholder=""
              input-style="text-align: right"
              @change="changeData(scope, 'mainCredit')"
              @focus="selectData($event, scope)"
              @keyup.enter="gotoNext($event, scope, 3)"
            />
          </template>
        </vxe-column>
        <vxe-column field="cashFlowsId" title="现金流量" width="110" align="right" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-select v-model="row.cashFlowsId" :options="options1"></vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="businessCode" title="业务号" width="110" align="center" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.businessCode" clearable></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="taxRebateRateId" title="退税率" width="100" align="right" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-select v-model="row.taxRebateRateId" :options="options2"></vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="projectId" title="项目名称" width="100" align="right" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-select v-model="row.projectId" :options="options3"></vxe-select>
          </template>
        </vxe-column>
      </ax-table>
    </el-main>
    <button @click="testHandle">test</button>
    <button @click="testHandle2">test2</button>
  </div>
</template>
<script setup>
import { Search } from '@element-plus/icons-vue';
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
import { nextTick, onMounted, ref } from 'vue';

import axTable from './index.vue';
import { mockList2 } from './list.ts';

const options1 = ref([]);
const options2 = ref([]);
const options3 = ref([]);

// 数据
const showAbstract = ref(false);
const rowIndex = ref(0);
const showSubject = ref(false);

const showCustomer = ref(false);
const showSupplier = ref(false);

const mainDebitTotalNew = ref(0);
const mainCreditTotalNew = ref(0);

const selectTableSubject = ref({});
const selectRowIndex = ref();

const tableDatas = ref(mockList2);
const selection = ref([]);
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
const column = ref([
  { type: 'checkbox', width: '50', align: 'center' },
  { type: 'seq', title: '#', width: '50', align: 'center' },
  {
    field: 'abstractName',
    title: '摘要',
    width: '130',
    align: 'center',
    slots: { edit: 'abstractName' },
    editRender: {},
  },
  {
    field: 'subjectIdName',
    title: '总帐科目',
    width: '260',
    align: 'center',
    slots: { edit: 'subjectIdName' },
    editRender: {},
  },
  {
    field: 'buysSalesIdName',
    title: '明细科目',
    minWidth: '230',
    align: 'center',
    slots: { edit: 'buysSalesIdName' },
    editRender: {},
  },
  {
    field: 'assistNumber',
    title: '原币数量',
    width: '110',
    align: 'center',
    slots: { edit: 'assistNumber' },
    editRender: {},
  },
  {
    field: 'rate',
    title: '汇率单价',
    width: '110',
    align: 'center',
    slots: { edit: 'rate' },
    editRender: {},
  },
  {
    field: 'mainDebit',
    title: '借方金额',
    width: '110',
    align: 'center',
    slots: { edit: 'mainDebit' },
    editRender: {},
  },
  {
    field: 'mainCredit',
    title: '货方金额',
    width: '110',
    align: 'center',
    slots: { edit: 'mainCredit' },
    editRender: {},
  },
  {
    field: 'cashFlowsId',
    title: '现金流量',
    width: '110',
    align: 'right',
    editRender: {
      name: 'select',
      options: [],
    },
  },
  {
    field: 'businessCode',
    title: '业务号',
    width: '110',
    align: 'center',
    editRender: {
      name: 'input',
    },
  },
  {
    field: 'taxRebateRateId',
    title: '退税率',
    width: '100',
    align: 'right',
    editRender: {
      name: 'select',
      options: [],
    },
  },
  {
    field: 'projectId',
    title: '项目名称',
    width: '100',
    align: 'right',
    editRender: {
      name: 'select',
      options: [],
    },
  },
]);

const table = ref();

function testHandle() {
  console.log(table.value);
  console.log(table.value.$refs.xGrid);
}

import demoApi from '@/api/demo';

function testHandle2() {
  demoApi.getList().then((res) => {
    console.log(res);
  });
}
// 数据定义
const selectionChange = (selection2) => {
  selection.value = selection2;
};
// 加载8行空数据
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const loadEightEmptyDatas = () => {
  for (let index = 0; index < 8; index++) {
    tableDatas.value.push(createEmptyData());
  }
};
// 创建空白数据
const createEmptyData = () => {
  return {
    assistNumber: '0.00',
    rate: '0.0000',
    mainDebit: '0.00',
    mainCredit: '0.00',
  };
};

// 选择摘要
const openAbstract = (scope) => {
  showAbstract.value = true;
  selectRowIndex.value = scope.rowIndex;
};

// 选择科目
const openSubject = (scope) => {
  showSubject.value = true;
  selectTableSubject.value = scope.row;
  selectRowIndex.value = scope.rowIndex;
};

const openBuysSale = (scope) => {
  if (scope.row.subjectId) {
    const prefix = scope.row.subjectId.substring(0, 4);
    if (['1121', '1122', '1123'].includes(prefix)) {
      showCustomer.value = true;
    } else if (['2201', '2202', '2203'].includes(prefix)) {
      showSupplier.value = true;
    }
    selectTableSubject.value = scope.row;
    selectRowIndex.value = scope.rowIndex;
  }
};

function footerMethod({ columns, data }) {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 3) {
      sums[index] = '合计';
      return;
    }
    if (index === 4) {
      sums[index] = '差额';
      return;
    }
    if (index <= 8 && index >= 5 && index !== 6) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          return !Number.isNaN(value) ? prev + curr : prev;
        }, 0)}`;
        sums[index] = `${Number(sums[index]).toFixed(2)}`;
      } else {
        sums[index] = '';
      }
    }
  });
  [mainDebitTotalNew.value, mainCreditTotalNew.value] = [sums[7], sums[8]];
  sums[4] = `差额: ${(Number(sums[7]) - Number(sums[8])).toFixed(2)}`;
  return [sums];
}

// 获取焦点的时候，选中文本框里面的数据
const selectData = (event, scope) => {
  console.log('scope', scope);
  rowIndex.value = scope.rowIndex;
  event.target.select();
};

// 计算汇率单价
const changeData = (scope, type) => {
  const isMainDebit =
    typeof Number(scope.row.mainDebit) === 'number' &&
    Number(scope.row.mainDebit) !== 0 &&
    Number(scope.row.assistNumber) !== 0;
  const isMainCredit =
    typeof Number(scope.row.mainCredit) === 'number' &&
    Number(scope.row.mainCredit) !== 0 &&
    Number(scope.row.assistNumber) !== 0;

  if (isMainDebit && type === 'mainDebit') {
    scope.row.rate = Number(scope.row.mainDebit) / Number(scope.row.assistNumber);
  } else if (isMainCredit && type === 'mainCredit') {
    scope.row.rate = Number(scope.row.mainCredit) / Number(scope.row.assistNumber);
  }
  if (Number(scope.row.mainDebit) === 0 && Number(scope.row.mainCredit) === 0) {
    scope.row.rate = '0.0000';
  }
  if (scope.row.rate) {
    scope.row.rate = Number(scope.row.rate).toFixed(4);
  }
};

// ------------------------打印逻辑结束--------------------------------------------------
// ------------------------凭证封面打印逻辑开始--------------------------------------------------
// ------------------------抵扣封面打印逻辑结束--------------------------------------------------

// 生命周期钩子
onMounted(() => {});
</script>

<style scoped>
.nopadding {
  height: 500px;
}
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 24px;
  height: 100%;
}

.custom-tree-node .code {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.custom-tree-node .do {
  display: none;
}

/* .custom-tree-node:hover .code {
	display: none;
} */

.custom-tree-node:hover .do {
  display: inline-block;
}

:global(.cell) {
  padding: 0;
}

/*选择组件元素设置 */
:deep(.el-input-group__append) {
  padding: 0 6px;
}

:deep(.cell) {
  padding: 0px;
}

:deep(.el-table__body-wrapper .el-table__cell) {
  padding: 0;
}

:deep(.el-form-item--default) {
  margin-bottom: 8px;
}

.nopadding :deep(.el-input__wrapper) {
  padding: 5px 5px;
  /*定义框高-宽 */
  background: transparent;
}

.nopadding :deep(.el-table__footer .cell) {
  text-align: right;
}

.nopadding :deep(.el-input__wrapper),
.nopadding :deep(.el-input-group__append) {
  box-shadow: none;
}

.menu :deep(.custom-tree-node[data-v-ddd379e2]) {
  padding-right: 8px;
  /*定义树右边距*/
}

.menu :deep(.el-tree-node__content > .el-tree-node__expand-icon) {
  padding: 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}
</style>
